// component/userauth/index.js
import urls from '../../utils/urls';
const app = getApp();

Component({
  attached: function(){
    console.log('attached');
    var that = this;
    //检测是否已经授权过了，没有则生成授权隐藏的窗口
    var userInfo = wx.getStorageSync('userinfo');
    wx.getSetting({
      success: res => {
        console.log(res,'auth');
        if (!res.authSetting['scope.userInfo'] || !userInfo['unionId']) {
          that.setData({
            showAuthBox: true,
          });

          this.wx_login();
        }
      }
    })
  },
  /**
   * 组件的属性列表
   */
  properties: {
  
  },

  /**
   * 组件的初始数据
   */
  data: {
    showAuthBox: false,
    showMask: false,
    code: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取code
    wx_login() {
      let that = this;
      wx.login({
        success(res) {
          that.setData({
            code: res.code
          })
        }
      })
    },
    //显示或隐藏
    targetMask: function(){
      let showMask = !this.data.showMask;
      this.setData({
        showMask: showMask,
      });
    },
    show: function(){
      this.setData({
        showMask: true,
      });
    },
    //获取信息
    getUserInfo: function(e) { 
      let that = this;

      let userInfo = e.detail.userInfo;
      userInfo.iv = e.detail.iv;
      userInfo.encryptedData = e.detail.encryptedData;
      userInfo.code = this.data.code;

      app.request({
        url: 'v2.login/union',
        data: userInfo,
        sCallback: (res) => {
          if(res.code == 1) {
              wx.setStorageSync('token', res.data.token);
              wx.setStorageSync('userinfo', res.data);

              that.setData({
                showMask: false,
                showAuthBox: false
              });
          } else {
            that.wx_login();
          }
        }
      })
    },
  }
})
